<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="nav-left">
        <span class="book-title">{{ bookTitle }}</span>
      </div>
      <div class="nav-right">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          format="YYYY/MM/DD"
          value-format="YYYY/MM/DD"
          @change="handleDateChange"
        />
        <el-select
          v-model="selectedWeather"
          placeholder="今日天气"
          @change="handleWeatherChange"
        >
          <el-option
            v-for="item in weatherOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <el-icon>
              <component :is="item.icon" />
            </el-icon>
            <span>{{ item.label }}</span>
          </el-option>
        </el-select>
        <el-button plain @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handlePublish">发布</el-button>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧日记目录 -->
      <div class="diary-sidebar">
        <div class="sidebar-header">
          <h3>日记目录</h3>
          <div class="header-actions">
<!--            <el-button type="text" @click="handleAddRootFolder">-->
<!--              <el-icon><Folder /></el-icon>-->
<!--              新建文件夹-->
<!--            </el-button>-->
<!--            <el-button type="text" @click="handleAddFile">-->
<!--              <el-icon><Document /></el-icon>-->
<!--              新建文件-->
<!--            </el-button>-->
          </div>
        </div>
        <div class="diary-list">
          <el-tree
            :data="diaryTreeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
            node-key="id"
            :highlight-current="true"
            ref="treeRef"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div class="node-content">
                  <el-icon v-if="data.type === 'folder'"><Folder /></el-icon>
                  <el-icon v-else><Document /></el-icon>
                  <span :class="{ active: currentDiary === data.id }">{{ node.label }}</span>
                </div>
                <div class="node-actions">
                  <template v-if="data.type === 'folder'">
                    <el-tooltip
                      content="新建文件夹"
                      placement="top"
                      :hide-after="500"
                      effect="dark"
                    >
                      <el-button 
                        type="text" 
                        @click.stop="handleAddSubFolder(data)"
                        class="action-btn"
                      >
                        <el-icon><FolderAdd /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip
                      content="新建文件"
                      placement="top"
                      :hide-after="500"
                      effect="dark"
                    >
                      <el-button 
                        type="text" 
                        @click.stop="handleAddFileInFolder(data)"
                        class="action-btn"
                      >
                        <el-icon><DocumentAdd /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </template>
                  <template v-if="data.type === 'diary'">
                    <el-icon v-if="data.weather"><component :is="data.weather.icon" /></el-icon>
                  </template>
                </div>
              </div>
            </template>
          </el-tree>

<!--          &lt;!&ndash; 新建文件夹输入框 &ndash;&gt;-->
<!--          <div v-if="showInput" class="folder-input-container" :style="folderInputStyle">-->
<!--            <el-input-->
<!--              v-model="newItemName"-->
<!--              :placeholder="createType === 'folder' ? '请输入文件夹名称' : '请输入文件名称'"-->
<!--              size="large"-->
<!--              @keyup.enter="confirmCreate"-->
<!--              ref="inputRef"-->
<!--            >-->
<!--              <template #prefix>-->
<!--                <el-icon><component :is="createType === 'folder' ? 'Folder' : 'Document'" /></el-icon>-->
<!--              </template>-->
<!--            </el-input>-->
<!--            <div class="parent-path" v-if="currentParentId">-->
<!--              <span class="label">位置：</span>-->
<!--              <span class="path">{{ getParentPath() }}</span>-->
<!--            </div>-->
<!--          </div>-->
        </div>
      </div>

      <!-- 右侧编辑区域 -->
      <div class="editor-section">
        <div class="title-input">
          <input
            v-model="diaryTitle"
            type="text"
            placeholder="写下今天的主题..."
            maxlength="100"
            @change="handleTitleChange"
          />
        </div>
        <div class="editor-container">
          <MdEditor
            :value="articleContent"
            :handleChange="handleEditorChange"
          />
        </div>
      </div>
    </div>

    <!-- 左侧历史记录 -->
    <div class="history-sidebar">
      <h3 class="sidebar-title">历史记录</h3>
      <div class="history-list">
        <div v-for="item in history"
             :key="item.id"
             class="history-item"
             @click="handleHistoryClick(item)">
          <div class="history-title">{{ item.title }}</div>
          <div class="history-meta">
            <span class="history-time">{{ formatTime(item.createTime) }}</span>
            <span class="history-status" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </span>
          </div>
        </div>
        <div v-if="history.length === 0" class="empty-history">
          暂无历史记录
        </div>
      </div>
    </div>

    <!-- 新建文件夹/文件弹出层 -->
    <el-dialog
      v-model="showInput"
      :title="createType === 'folder' ? '新建文件夹' : '新建文件'"
      width="480px"
      :close-on-click-modal="false"
      :show-close="false"
      class="create-dialog"
      top="20vh"
    >
      <div class="dialog-body">
        <div class="icon-header">
          <el-icon :size="48" :class="createType">
            <component :is="createType === 'folder' ? 'FolderAdd' : 'DocumentAdd'" />
          </el-icon>
        </div>
        <el-input
          v-model="newItemName"
          :placeholder="createType === 'folder' ? '请输入文件夹名称' : '请输入文件名称'"
          size="large"
          @keyup.enter="confirmCreate"
          ref="inputRef"
          class="name-input"
        >
          <template #prefix>
            <el-icon><component :is="createType === 'folder' ? 'Folder' : 'Document'" /></el-icon>
          </template>
        </el-input>
        <div class="parent-path" v-if="currentParentId">
          <el-tag size="small" class="path-tag">
            <el-icon><FolderOpened /></el-icon>
            <span>{{ getParentPath() }}</span>
          </el-tag>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelCreate" size="large">取消</el-button>
          <el-button type="primary" @click="confirmCreate" size="large">
            {{ createType === 'folder' ? '创建文件夹' : '创建文件' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import {
  Sunny,
  Cloudy,
  Lightning,
  Moon,
  Folder,
  FolderOpened,
  Document,
  FolderAdd,
  DocumentAdd,
  Plus,
  Check,
  Close
} from '@element-plus/icons-vue'
import MdEditor from '/@/components/MdEditor.vue'
import { ArticleControllerService, type ArticleDTO, type ArticleVO, type PageArticleVO } from '/@/api/openapi'
import { useUserStore } from '/@/store'
import { ElMessage } from 'element-plus'

interface Weather {
  value: string
  label: string
  icon: string
}

interface TreeNode {
  id: string | number
  label: string
  type: 'folder' | 'diary'
  children?: TreeNode[]
  weather?: Weather
  content?: string
  date?: string
}

interface HistoryItem {
  id: number
  title: string
  createTime: string
  status: number
}

const uuid = (len: number, radix: number) => {
  var chars =
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  var uuid = [],
    i
  radix = radix || chars.length

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    // rfc4122, version 4 form
    var r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}

const uuidString = uuid(8, 2)

// 天气选项
const weatherOptions = [
  { value: 'sunny', label: '晴天', icon: 'Sunny' },
  { value: 'cloudy', label: '多云', icon: 'Cloudy' },
  { value: 'rainy', label: '下雨', icon: 'Lightning' },
  { value: 'night', label: '夜晚', icon: 'Moon' },
]

// 基本信息
const bookTitle = ref('测试')
const selectedDate = ref(new Date().toISOString().split('T')[0])
const selectedWeather = ref('sunny')
const diaryTitle = ref('')
const articleContent = ref('')
const currentDiary = ref<string | number>(0)

// 树形结构配置
const defaultProps = {
  children: 'children',
  label: 'label',
}

// Mock数据 - 树形结构
const diaryTreeData = ref<TreeNode[]>([
  {
    id: '1',
    label: '2024年',
    type: 'folder',
    children: [
      {
        id: '1-1',
        label: '第一季度',
        type: 'folder',
        children: [
          {
            id: '1-1-1',
            label: '我的第一篇日记',
            type: 'diary',
            date: '2024/01/01',
            weather: weatherOptions[0],
            content: '这是我的第一篇日记内容...'
          },
          {
            id: '1-1-2',
            label: '春节快乐',
            type: 'diary',
            date: '2024/02/10',
            weather: weatherOptions[1],
            content: '新年快乐！'
          }
        ]
      },
      {
        id: '1-2',
        label: '第二季度',
        type: 'folder',
        children: []
      }
    ]
  },
  {
    id: '2',
    label: '个人随笔',
    type: 'folder',
    children: [
      {
        id: '2-1',
        label: '读书笔记',
        type: 'folder',
        children: [
          {
            id: '2-1-1',
            label: '读《三体》有感',
            type: 'diary',
            date: '2024/03/15',
            weather: weatherOptions[2],
            content: '今天读完了《三体》...'
          }
        ]
      }
    ]
  }
])

// 处理日期变化
const handleDateChange = (date: string) => {
  if (!date) return

  const existingDiary = diaryTreeData.value.find(d => d.date === date)
  if (existingDiary) {
    handleNodeClick(existingDiary)
  } else {
    createNewDiary(date)
  }
}

// 处理天气变化
const handleWeatherChange = (weather: string) => {
  const currentDiaryData = diaryTreeData.value.find(
    d => d.id === currentDiary.value,
  )
  if (currentDiaryData) {
    currentDiaryData.weather =
      weatherOptions.find(w => w.value === weather) || weatherOptions[0]
  }
}

// 创建新日记
const createNewDiary = (date: string) => {
  const newDiary: TreeNode = {
    id: Date.now(),
    label: '',
    type: 'diary',
    date,
    weather:
      weatherOptions.find(w => w.value === selectedWeather.value) ||
      weatherOptions[0],
  }
  diaryTreeData.value.push(newDiary)
  currentDiary.value = newDiary.id
  diaryTitle.value = ''
  articleContent.value = ''
}

// 处理节点点击
const handleNodeClick = (data: TreeNode) => {
  if (data.type === 'diary') {
    currentDiary.value = data.id
    diaryTitle.value = data.label
    articleContent.value = data.content || ''
    selectedDate.value = data.date || new Date().toISOString().split('T')[0]
    selectedWeather.value = data.weather?.value || 'sunny'
  }
}

// 处理标题变化
const handleTitleChange = () => {
  const currentDiaryData = diaryTreeData.value.find(
    d => d.id === currentDiary.value,
  )
  if (currentDiaryData) {
    currentDiaryData.label = diaryTitle.value
  }
}

// 处理编辑器内容变化
const handleEditorChange = (value: string) => {
  articleContent.value = value
  const currentDiaryData = diaryTreeData.value.find(
    d => d.id === currentDiary.value,
  )
  if (currentDiaryData) {
    currentDiaryData.content = value
  }
}

const userStore = useUserStore()

const history = ref<HistoryItem[]>([])

onMounted(() => {
  loadData()
})
const loadData = () => {
  ArticleControllerService.getArticlePage({
    pageNum: 1,
    pageSize: 10,
    uid: userStore.getUserId(),
  }).then(res => {
    if(res?.data?.records) {
      history.value = res.data.records.map(item => ({
        id: item.id ?? 0,
        title: item.title ?? '',
        createTime: item.createTime ?? '',
        status: item.status ?? 0
      }))
    } else {
      history.value = []
    }
  }).catch(error => {
    console.error('加载历史记录失败:', error)
    history.value = []
  })
}

// 保存草稿
const handleSave = async () => {
  await publishDiary(0)
}

// 发布日记
const handlePublish = async () => {
  await publishDiary(1)
}

const publishDiary = async (status: number) => {
  if (!userStore.getUserId()) {
    ElMessage.warning('请先登录,才能保存日记')
    return
  }

  if (!diaryTitle.value || !articleContent.value) {
    ElMessage.warning('请填写标题和内容')
    return
  }
  const data: ArticleDTO = {
    title: diaryTitle.value,
    content: articleContent.value,
    status: status,
    createdBy: userStore.getUserId(),
    createDate: selectedDate.value,
    weather: selectedWeather.value,
    uuid: uuidString,
  }
  console.log(data)
  try {
    ArticleControllerService.addArticle(data)
      .then(res => {
        if (res.data) {
          ElMessage.success('保存成功')
          createNewDiary(selectedDate.value)
        } else {
          ElMessage.error('保存失败，请稍后重试')
        }
      })
      .catch(error => {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请稍后重试')
      })
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '草稿'
    case 1:
      return '已发布'
    default:
      return '未知'
  }
}

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 0:
      return 'draft'
    case 1:
      return 'published'
    default:
      return ''
  }
}

// 处理历史记录点击
const handleHistoryClick = (item: HistoryItem) => {
  // 这里可以添加点击历史记录后的处理逻辑
  console.log('点击历史记录:', item)
}

const treeRef = ref()
const folderInputRef = ref()
const showInput = ref(false)
const newItemName = ref('')
const currentParentId = ref<string | number>('')
const folderInputStyle = ref({
  top: '0px'
})
const createType = ref<'folder' | 'file'>('folder')
const inputRef = ref()

// 处理添加根目录文件夹
const handleAddRootFolder = () => {
  createType.value = 'folder'
  currentParentId.value = ''
  showInput.value = true
  newItemName.value = ''
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 处理添加子文件夹
const handleAddSubFolder = (parentNode: TreeNode) => {
  createType.value = 'folder'
  currentParentId.value = parentNode.id
  showInput.value = true
  newItemName.value = ''
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 在指定文件夹下新建文件
const handleAddFileInFolder = (parentNode: TreeNode) => {
  createType.value = 'file'
  currentParentId.value = parentNode.id
  showInput.value = true
  newItemName.value = ''
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 获取父级路径
const getParentPath = () => {
  if (!currentParentId.value) return '根目录'
  const parent = findFolderById(diaryTreeData.value, currentParentId.value)
  return parent ? parent.label : '根目录'
}

// 确认创建
const confirmCreate = () => {
  console.log("点击了创建");
  console.log(showInput.value)
  if (showInput.value) {
    showInput.value = false
  }
  if (!newItemName.value.trim()) {
    ElMessage.warning(createType.value === 'folder' ? '请输入文件夹名称' : '请输入文件名称')
    return
  }

  if (createType.value === 'folder') {
    const newFolder: TreeNode = {
      id: Date.now(),
      label: newItemName.value.trim(),
      type: 'folder',
      children: []
    }

    if (!currentParentId.value) {
      diaryTreeData.value.push(newFolder)
    } else {
      const parentFolder = findFolderById(diaryTreeData.value, currentParentId.value)
      if (parentFolder) {
        parentFolder.children = parentFolder.children || []
        parentFolder.children.push(newFolder)
      }
    }
  } else {
    const newFile: TreeNode = {
      id: Date.now(),
      label: newItemName.value.trim(),
      type: 'diary',
      date: new Date().toISOString().split('T')[0],
      weather: weatherOptions[0],
      content: ''
    }

    if (!currentParentId.value) {
      diaryTreeData.value.push(newFile)
    } else {
      const parentFolder = findFolderById(diaryTreeData.value, currentParentId.value)
      if (parentFolder) {
        parentFolder.children = parentFolder.children || []
        parentFolder.children.push(newFile)
      }
    }
  }

  showInput.value = false
  newItemName.value = ''
  ElMessage.success(createType.value === 'folder' ? '文件夹创建成功' : '文件创建成功')
}

// 取消创建
const cancelCreate = () => {
  console.log("点击了取消")
  showInput.value = false
  newItemName.value = ''
}

// 递归查找文件夹
const findFolderById = (nodes: TreeNode[], id: string | number): TreeNode | null => {
  for (const node of nodes) {
    if (node.id === id) {
      return node
    }
    if (node.children) {
      const found = findFolderById(node.children, id)
      if (found) {
        return found
      }
    }
  }
  return null
}
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.top-nav {
  height: 56px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .nav-left {
    .book-title {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .nav-right {
    display: flex;
    gap: 12px;
    align-items: center;

    .el-date-picker {
      width: 140px;
    }

    .el-select {
      width: 120px;
    }
  }
}

.main-content {
  flex: 1;
  display: flex;
  height: calc(100vh - 56px);
}

.diary-sidebar {
  width: 250px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;

  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .diary-list {
    flex: 1;
    overflow-y: auto;
    padding: 12px 0;

    :deep(.el-tree-node) {
      .el-tree-node__content {
        height: 32px;

        &:hover {
          .node-actions {
            opacity: 1;
          }
        }
      }

      &:focus > .el-tree-node__content {
        background-color: #f5f7fa;
      }
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      width: 100%;

      .node-content {
        display: flex;
        align-items: center;
        gap: 8px;

        .active {
          color: #409eff;
          font-weight: 500;
        }
      }

      .node-actions {
        display: flex;
        gap: 4px;
        align-items: center;
        opacity: 0;
        transition: opacity 0.3s ease;

        :deep(.el-tooltip__trigger) {
          line-height: 1;
        }

        .action-btn {
          padding: 2px;
          font-size: 14px;
          color: #606266;
          height: auto;
          line-height: 1;

          &:hover {
            color: #409eff;
          }
        }
      }
    }
  }

  .folder-input-container {
    position: fixed;
    left: 220px;
    z-index: 1000;
    width: 200px;
    background: white;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
}

.editor-section {
  flex: 1;
  padding: 20px;
  overflow-y: auto;

  .title-input {
    margin-bottom: 20px;

    input {
      width: 100%;
      padding: 15px 20px;
      font-size: 18px;
      border: 1px solid #ddd;
      border-radius: 8px;
      outline: none;
      background: #fff;

      &:focus {
        border-color: #409eff;
      }

      &::placeholder {
        color: #999;
      }
    }
  }

  .editor-container {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    min-height: calc(100vh - 200px);
  }
}

.history-sidebar {
  width: 250px;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 20px;
  height: fit-content;

  .sidebar-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .history-list {
    .history-item {
      padding: 12px;
      border-bottom: 1px solid #f5f5f5;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #f5f5f5;
      }

      .history-title {
        font-size: 14px;
        color: #333;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }

      .history-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #999;

        .history-time {
          color: #666;
        }

        .history-status {
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 12px;

          &.draft {
            background: #f0f0f0;
            color: #666;
          }

          &.published {
            background: #e6f7ff;
            color: #1890ff;
          }
        }
      }
    }

    .empty-history {
      text-align: center;
      color: #999;
      padding: 20px;
      font-size: 14px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.create-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(4px);
}

.create-dialog {
  border-radius: 8px;
  
  .el-dialog__header {
    margin: 0;
    padding: 20px 20px 0;
    text-align: center;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .el-dialog__body {
    padding: 30px 40px;
  }

  .el-dialog__footer {
    padding: 20px;
    border-top: 1px solid #f0f0f0;
  }
}

.dialog-body {
  .icon-header {
    text-align: center;
    margin-bottom: 24px;

    .el-icon {
      padding: 16px;
      border-radius: 50%;
      background: #f5f7fa;

      &.folder {
        color: #e6a23c;
      }

      &.file {
        color: #409eff;
      }
    }
  }

  .name-input {
    margin-bottom: 16px;

    :deep(.el-input__wrapper) {
      padding: 4px 12px;
    }

    :deep(.el-input__inner) {
      height: 42px;
      font-size: 16px;
    }

    .el-icon {
      font-size: 18px;
      margin-right: 8px;
    }
  }

  .parent-path {
    margin-top: 16px;
    
    .path-tag {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      padding: 6px 10px;
      background: #f5f7fa;
      border: none;
      color: #606266;

      .el-icon {
        margin-right: 2px;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    min-width: 100px;
    padding: 12px 20px;
    font-size: 14px;
  }
}
</style>
